package com.evaluation.config;

import com.evaluation.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

/**
 * Web配置类
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        // 静态资源
                        "/static/**", "/css/**", "/js/**", "/images/**", "/favicon.ico",
                        // H5页面
                        "/h5/**", "/evaluation/h5/**",
                        // PC管理页面
                        "/admin/**", "/evaluation/admin/**",
                        // 登录相关API (不需要拦截)
                        "/", "/evaluation/health", "/evaluation/", "/evaluation/api/h5/auth/check", "/evaluation/api/h5/auth/logout",
                        "/login", "/login/admin", "/login/wechat", "/weixin/login",
                        "/evaluation/api/admin/login", "/evaluation/api/admin/check", "/evaluation/api/admin/logout", "/evaluation/api/admin/captcha",
                        // 企业微信相关路径
                        "/evaluation/wechat/**", "/wechat/**",
                        // 测试页面和错误页面
                        "/evaluation/wechat-test.html", "/evaluation/wechat-error.html",
                        // API文档等
                        "/swagger-ui/**", "/v3/api-docs/**"
                );
    }

    /**
     * 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }

    /**
     * 静态资源配置
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");

        registry.addResourceHandler("/h5/**")
                .addResourceLocations("classpath:/static/h5/");

        registry.addResourceHandler("/admin/**")
                .addResourceLocations("classpath:/static/admin/");
    }

    /**
     * 默认页面配置
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 根路径使用login模板，该模板会自动重定向到H5页面
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/evaluation").setViewName("login");
    }
}
